package it.amicosmanettone.utils.torcia;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	Camera cam = null;
	Boolean on = false;
	TextView HeadMessage;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		
		HeadMessage = (TextView) findViewById(R.id.textMessage);
		
		final Button buttonOnOff = (Button)findViewById(R.id.buttonOnOff);
		
		if(verifyConnection(this)){
			
			new DownloadMessage().execute();
			
		}
		
		flashOn();
		
		buttonOnOff.setText("Spegni la torcia");
		
		buttonOnOff.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				
				if(on){
					
					cam.stopPreview();
				    cam.release();
				    on = false;
				    buttonOnOff.setText("Accendi la torcia");
					
				}else{
					
					flashOn();
					buttonOnOff.setText("Spegni la torcia");
					
				}
				
				
				
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case android.R.id.home:

			return true;
			
		case R.id.action_info:
			
			Intent informationActivity = new Intent(this, InformationActivity.class);
			startActivity(informationActivity);
			
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void flashOn(){
		cam = Camera.open();     
		Parameters p = cam.getParameters();
		p.setFlashMode(Parameters.FLASH_MODE_TORCH);
		cam.setParameters(p);
		cam.startPreview();
		on = true;
	}
	
	class DownloadMessage extends AsyncTask<Void, Void, String> {

		public String urlMessage = "http://www.amicosmanettone.it/api/msg/messTorcia.html";
		int timeoutConnection = 3000;//Timeout connection..
		int timeoutSocket = 3000;//Timeout data...
		public static final String DEFAULT_MESSAGE = "";

		@Override
		protected String doInBackground(Void... params) {

			String out = "";
			HttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
			HttpClient httpclient = new DefaultHttpClient(httpParameters);
			HttpGet httpget = new HttpGet(urlMessage);
			Log.v("AsyncTaskMsg", "Try to download message: "+urlMessage);
			try {
				HttpResponse response = httpclient.execute(httpget);
				HttpEntity responseEntity = response.getEntity();
				StringBuffer readed = new StringBuffer();
				if (responseEntity != null) {
					if (response.getStatusLine().getStatusCode() != 404) {
						BufferedReader in = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
						int result;
						while ((result = in.read()) != -1) {
							readed.append(Character.toChars(result));
						}//End while...
						String readString = readed.toString();
						if (readString.length() >2) {
							
							out = readString;
						}
						Log.v("AsyncTaskMsg", "Message retrieved: "+out);
						//Log.v("AsyncTaskMsg", "Response from server: "+out);
					} else {
						return (out);
					}

				}else{
					//Log.v("AsyncTaskMsg", "responseEntity null");
				}

				
			} catch (Exception e) {
				//Log.w("AsyncTaskMsg", "Exception on download...");
				e.printStackTrace();
				out=DEFAULT_MESSAGE;
				//return (MercatinoActivity.DEFAULT_MESSAGE);
			}// End try...catch...
			
			

			return out;
		}

		protected void onPostExecute(String result) {

			HeadMessage.setText(result);

		}

	}// End class
	
	
	protected void onDestroy() {
	    super.onDestroy();
	    if(on){
	    	
	    	cam.stopPreview();
		    cam.release();
	    	
	    }
	    
	}
	
	public static boolean verifyConnection(Context context) {

		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo netInfo = cm.getActiveNetworkInfo();

		if (netInfo != null && netInfo.isConnectedOrConnecting()) {

			return true;

		}

		return false;

	}
	
	
	public void onClickShareBarButton(View view) {
		Intent sharingIntent = new Intent(Intent.ACTION_SEND);
		sharingIntent.setType("text/plain");
		sharingIntent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=it.amicosmanettone.utils.torcia");
		sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Prova Torcia, l\'applicazione che ti permette di vedere al buio!");
		startActivity(Intent.createChooser(sharingIntent, "Suggerisci tramite"));
	}
	
}
